package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
//11
@Service(interfaceClass = CheckGroupService.class)
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupMapper checkGroupMapper;

    //新增检查组
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        //新增检查组
        checkGroupMapper.addCheckGroup(checkGroup);
        //设置检查项和检查组的中间表
        setCheckGroupAndCheckItem(checkitemIds, checkGroup.getId());
    }
    //设置检查项和检查组的中间表
    private void setCheckGroupAndCheckItem(Integer[] checkitemIds, Integer id) {
        //设置检查项和检查组的中间表
        if (checkitemIds != null && checkitemIds.length > 0) {

            for (Integer checkItemId : checkitemIds) {
                //循环设置中间表关系
                checkGroupMapper.setCheckGroupAndCheckItem(checkItemId, id);
            }
        }
    }

    //分页查询检查组
    @Override
    public PageResult findByPage(Integer currentPage, Integer pageSize, String queryString) {
        //获取第1页，10条内容，默认查询总数count
        PageHelper.startPage(currentPage, pageSize);
        List<CheckGroup> list = checkGroupMapper.findByPage(queryString);
        //用PageInfo对结果进行包装
        PageInfo<CheckGroup> pageInfo = new PageInfo<>(list);
        //将分页数据封装到PageResult
        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    //检查组删除
    @Override
    public void deleteById(Integer id) {
        //检查当前有没有被引用
        Integer count=checkGroupMapper.findCountById(id);
        if (count>0) {
            throw new RuntimeException(MessageConstant.CHECKGROUP_IS_QUOTED);
        }
        checkGroupMapper.deleteById(id);
    }

    //编辑检查组
    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //删除中间表关系
        checkGroupMapper.deleteAssociation(checkGroup.getId());
        //更新检查项
        checkGroupMapper.edit(checkGroup);
        //设置检查项和检查组的中间表
        setCheckGroupAndCheckItem(checkitemIds, checkGroup.getId());
    }

    //查询所有检查组
    @Override
    public List<CheckGroup> findCheckGroup() {
        List<CheckGroup> checkGroupList=checkGroupMapper.findCheckGroup();
        return checkGroupList;
    }
}